<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
        <el-form-item label="客户" prop="roleName">
          <el-select v-model="value" placeholder="无数据" style="width: 300px" @change="getList">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="询价单名称" prop="roleName" label-width="100" v-if="dataInfo.title3">
           <span style="color: #F56C6C;">{{dataInfo.title2}}</span>
        </el-form-item>
        <el-form-item label="询价单编号" prop="roleName" label-width="100" v-if="dataInfo.title3">
           <span style="color: #F56C6C;">{{dataInfo.title3}}</span>
        </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5" v-if="dataInfo.title1">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">继续添加</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport">上传文件</el-button>
      </el-col>
      <el-col :span="1.5" v-if="dataInfo.title1">
        <el-button type="warning" plain icon="Timer" @click="handleSave">临时保存</el-button>
      </el-col>
      <el-col :span="1.5" v-if="dataInfo.title1">
        <el-button type="primary" plain icon="QuestionFilled" @click="handleMatching">匹配报价</el-button>
      </el-col>
      <el-col :span="1.5" v-if="dataInfo.title1">
        <el-tooltip content="全部匹配报价后，可导出" :disabled="canExport" placement="top">
          <div>
            <el-button type="success" plain icon="Download" @click="handleExport" :disabled="!canExport">
              导出询价
            </el-button>
          </div>
        </el-tooltip>
      </el-col>
      <!-- 添加图例 -->
      <!-- <el-col :span="11" class="legend-container" v-if="canExport">
        <div class="legend-item">
          <span class="legend-color green_bg"></span> 匹配成功
        </div>
        <div class="legend-item">
          <span class="legend-color yellow_bg"></span> 匹配多个
        </div>
        <div class="legend-item">
          <span class="legend-color red_bg"></span> 未匹配(需添加物料)
        </div>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" :isRefresh="false" :columns="columns"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table ref="tableRef" v-loading="loading" size="large" :indent="50" :max-height="tableHeight" :data="dataList"
      row-key="autoBillID" :tree-props="{ children: 'childMaterial' }">
      <el-table-column type="index" label="序号" width="60" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" v-if="columns[0].visible" prop="billName" align="center" width="250" />
      <el-table-column label="物料号" v-if="columns[1].visible" prop="billMaterialNO" align="center" width="200" />
      <el-table-column label="型号" v-if="columns[2].visible" prop="billTypes" align="center" width="200" />
      <el-table-column label="规格" v-if="columns[3].visible" prop="billSpecifications" align="center" width="200" />
      <el-table-column label="数量" v-if="columns[4].visible" prop="billRemaining" align="center" width="80" />
      <el-table-column label="单位" v-if="columns[5].visible" prop="billUnit" align="center" width="80" />
      <el-table-column label="采购备注" v-if="columns[6].visible" prop="billManufacturer" align="center" width="200" />
      <el-table-column label="成本(元)" v-if="columns[7].visible" prop="unitCost1" align="center" width="100">
        <template #default="scope">
          <span :class="getColorClass(scope.row)">
            {{ getTotalCost(scope.row,'unitCost1') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="总成本(元)" v-if="columns[8].visible" prop="totalCost" align="center" width="100">
        <template #default="scope">
          <span :class="getColorClass(scope.row)">
            {{ getTotalCost(scope.row,'totalCost') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="单价(元)" v-if="columns[9].visible" prop="unitPrice" align="center" width="100">
        <template #default="scope">
          <span :class="getColorClass(scope.row)">
            {{ getTotalCost(scope.row,'unitPrice') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="金额(元)" v-if="columns[10].visible" prop="totalPrice" align="center" width="100">
        <template #default="scope">
          <span :class="getColorClass(scope.row)">
            {{ getTotalCost(scope.row,'totalPrice') }}
          </span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="150px" align="center" class-name="small-padding fixed-width">
        <template #default="scope" >
          <template v-if="!scope.row.childMaterial">
            <!-- status=1已匹配  materialID 0为未匹配成功，-1为匹配到多个 -2父节点不需要匹配，其余为一对一匹配成功-->
            <!-- <el-button v-if="scope.row.materialID == 0 && scope.row.status == 1" link type="primary" icon="Plus"
              @click="addWl(scope.row)">新增物料</el-button> -->
            <el-button  link type="primary" icon="Edit" :disabled="!canExport"
              @click="selWl(scope.$index,scope.row)">修改</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <!-- 
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" /> -->

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef" :model="rowForm" :rules="rules" label-width="100px">
        <el-row>
          <template v-if="!rowDisabled">
            <el-col :span="8">
              <el-form-item label="名称" prop="billName">
                <el-input v-model.trim="rowForm.billName" :disabled="rowDisabled"
                  :placeholder="rowDisabled ? '' : '请输入名称'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格" prop="billSpecifications">
                <template #label>
                  <span class="required-star">*</span> 规格
                </template>
                <el-input v-model.trim="rowForm.billSpecifications" :disabled="rowDisabled"
                  :placeholder="rowDisabled ? '' : '请输入规格'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="型号" prop="billTypes">
                <template #label>
                  <span class="required-star">*</span> 型号
                </template>
                <el-input v-model.trim="rowForm.billTypes" :disabled="rowDisabled"
                  :placeholder="rowDisabled ? '' : '请输入型号'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="数量" prop="billRemaining">
                <el-input v-model.trim="rowForm.billRemaining" type="number" :disabled="rowDisabled"
                  :placeholder="rowDisabled?'':'请输入数量'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="父级菜单">
                <!-- <el-cascader v-model="rowForm.parentsID" ref="cascaderRef" :options="optionsParents"
                  :props="{ checkStrictly: true, emitPath: false, children: 'childMaterial', value: 'autoBillID', label: 'billName', }"
                  :show-all-levels="false" @change="handleCascaderChange" /> -->
                <el-select v-model="rowForm.parentsID" clearable placeholder="选择父级" style="width: 240px">
                  <el-option v-for="item in optionsParents" :key="item.autoBillID" :label="item.billName"
                    :value="item.autoBillID" />
                </el-select>
              </el-form-item>
            </el-col>
          </template>
          <template v-else>
            <el-col :span="8">
              <el-form-item label="名称">
                <el-input v-model.trim="rowForm.billName" :disabled="rowDisabled"
                  :placeholder="rowDisabled ? '' : '请输入名称'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格">
                <el-input v-model.trim="rowForm.billSpecifications" :disabled="rowDisabled"
                  :placeholder="rowDisabled ? '' : '请输入规格'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="型号">
                <el-input v-model.trim="rowForm.billTypes" :disabled="rowDisabled"
                  :placeholder="rowDisabled ? '' : '请输入型号'" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="数量">
                <el-input v-model.trim="rowForm.billRemaining" type="number" :disabled="rowDisabled"
                  :placeholder="rowDisabled?'':'请输入数量'" />
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="8">
            <el-form-item label="单位">
              <el-input v-model.trim="rowForm.billUnit" :disabled="rowDisabled" :placeholder="rowDisabled?'':'请输入单位'" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="采购备注">
              <el-input v-model.trim="rowForm.billManufacturer" :disabled="rowDisabled"
                :placeholder="rowDisabled?'':'请输入采购备注'" />
            </el-form-item>
          </el-col>
          <template v-if="rowDisabled">
            <el-col :span="8">
              <el-form-item label="成本" prop="unitCost">
                <el-input-number 
                v-model="displayCost" 
                :step="costUnit_=== '元' ? 0.01 : 1" 
                :step-strictly="costUnit_=== '分'? true : false"
                :max="100000000" 
                :precision="costUnit_=== '元' ? 2 : 0" 
                @change="UpdateSellingPrice2"
              > 
                <template #suffix>
                  <el-dropdown @command="handleCommand" trigger="click">
                    <span>{{ costUnit_ }}
                      <el-icon size="10"><ArrowDown /></el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="分">分</el-dropdown-item>
                        <el-dropdown-item command="元">元</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </template>
              </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="税率" prop="taxRate">
                <el-input-number v-model="rowForm.taxRate" :step="0.1" :precision="4" :max="100000000"
                  @change="UpdateSellingPrice2">
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="利润率" prop="profitRate">
                <el-input-number v-model="rowForm.profitRate" :step="0.1" :precision="4" :max="100000000"
                  @change="UpdateSellingPrice2">
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="折扣率" prop="discount">
                <el-input-number v-model="rowForm.discount" :step="0.1" :precision="4" :max="100000000"
                  @change="UpdateSellingPrice2">
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="优惠" prop="preferential">
                <el-input-number v-model="rowForm.preferential" step-strictly :max="100000000"
                  @change="UpdateSellingPrice2">
                  <template #suffix>
                    <span>分</span>
                  </template>
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单价">
                <el-input-number v-model="rowForm.unitPrice" :disabled="true" :precision="3" :max="100000000">
                  <template #suffix>
                    <span>元</span>
                  </template>
                </el-input-number>
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="600px" append-to-body :close-on-click-modal="false">
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 物料添加弹窗 -->
    <SupplyDialog :open="showSupplyDialog" :title="supplyDialogTitle" :form="supplyForm" :rules="supplyRules"
      :options="Propsoptions" :options2="Propsoptions2" :options3="Propsoptions3" :options4="Propsoptions4"
      :options5="Propsoptions5" :options6="Propsoptions6" @submitForm="handleSupplySubmit"
      @cancel="showSupplyDialog = false" @changeOpt5="handleSupplyChangeOpt5"
      @updateSellingPrice="handleSupplyUpdateSellingPrice" />
    <!-- 选择物料弹窗 -->
    <MaterialTable ref="materialTableRef" v-model="dialogVisible" @cancel="dialogVisible = false" 
    :queryParams="queryParams2"  @select="handleMaterialSelect" @onInput="onInput" />
  </div>
</template>

<script setup name="Role">
import { getToken } from "@/utils/auth";
import { GetTenantPageList, AddTenant, EditTenant, DelTenant } from "@/api/system/tenant";
import { useInfoStore } from '@/store/modules/info.js'
import SupplyDialog from './components/SupplyDialog.vue';
import MaterialTable from './components/MaterialTable.vue';
const router = useRouter();
const tableHeight = ref(document.documentElement.scrollHeight - 250 + "px");
const userInfo = useInfoStore();
const { proxy } = getCurrentInstance();
const dataInfo = ref([]);
const dataList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const dateRange = ref([]);
const deptRef = ref(null);
const options = ref([]);
const optionsParents = ref([]);
const value = ref(null);
// const reName = ref('1FEE9D01E7E344EDB41CBB8178E2CAFC.xlsx');//文件名称
const reName = ref();//文件名称
const rowForm = ref({});//
const rowDisabled = ref(true);//是否编辑
const costUnit_ = ref('元');//成本显示单位 默认分
const isExport = ref(false);//是否导出
const selIndex = ref(false);//选中的索引
const selItem = ref(false);//选中的子item
const isZ = ref(false);//是否是子节点




/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/api/Upload/UploadFile"
});
// 列显隐信息
const columns = ref([
  { key: 0, label: `名称`, visible: true },
  { key: 1, label: `物料号`, visible: false },
  { key: 2, label: `型号`, visible: false },
  { key: 3, label: `规格`, visible: true },
  { key: 4, label: `数量`, visible: true },
  { key: 5, label: `单位`, visible: true },
  { key: 6, label: `采购备注`, visible: true },
  { key: 7, label: `成本`, visible: true },
  { key: 8, label: `总成本`, visible: true },
  { key: 9, label: `单价`, visible: true },
  { key: 10, label: `金额`, visible: true },
  
]);
const data = reactive({
  form: {
    tenantName: null,
    tenantDoMain: null,
    tenantDes: null,
    tenantOrders: 0,
    id: null,
    price: null
  },
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    Tenantname: null,
  },
  queryParams2:{
      name: null,
      specifications: null,
  },
  rules: {
    billName: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    billRemaining: [
      { required: true, message: "数量不能为空", trigger: "blur" }
    ],
    billTypes: [{
      validator: (rule, value, callback) => {
        if (!rowForm.value.billTypes && !rowForm.value.billSpecifications) {
          callback(new Error('规格和型号至少填写一项'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
    billSpecifications: [{
      validator: (rule, value, callback) => {
        if (!rowForm.value.billTypes && !rowForm.value.billSpecifications) {
          callback(new Error('规格和型号至少填写一项'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }],
    unitCost: [{ required: true, message: "成本不能为空", trigger: "blur" }],
    taxRate: [{ required: true, message: "税率不能为空", trigger: "blur" }],
    profitRate: [{ required: true, message: "利润率不能为空", trigger: "blur" }],
    discount: [{ required: true, message: "折扣率不能为空", trigger: "blur" }],
    preferential: [{ required: true, message: "优惠不能为空", trigger: "blur" }],
  },
});
const { queryParams, form, rules,queryParams2 } = toRefs(data);
// 组件
const Propsoptions = ref([]);
const Propsoptions2 = ref([]);
const Propsoptions3 = ref([]);
const Propsoptions4 = ref([]);
const Propsoptions5 = ref([]);
const Propsoptions6 = ref([]);
const showSupplyDialog = ref(false);
const supplyDialogTitle = ref("新增物料");
const selId = ref(null);
const supplyForm = ref({
  id: null,
  classCode: null,
  classNum: null,
  name: null,
  reName: null,
  resource: null,
  specifications: null,
  types: null,
  styles: null,
  colors: null,
  level: null,
  remaining: 0,
  unit: null,
  unit_V: '单位',
  manufacturer: null,
  barcode: null,
  warmLevel: 0,
  takeTime: 0,
  price: {
    cost: 0,
    profitRate: 1,
    taxRate: 1,
    discount: 1,
    preferential: 0,
    price1Show: 0
  },
  repository: null
});
// 添加物料表单校验规则
const supplyRules = ref({
  name: [{ required: true, message: "物料名称不能为空", trigger: "blur" }],
  'price.cost': [{ required: true, message: "成本不能为空", trigger: "blur" }],
  'price.taxRate': [{ required: true, message: "税率不能为空", trigger: "blur" }],
  'price.profitRate': [{ required: true, message: "利润率不能为空", trigger: "blur" }],
  'price.discount': [{ required: true, message: "折扣率不能为空", trigger: "blur" }],
  'price.preferential': [{ required: true, message: "优惠不能为空", trigger: "blur" }],
  types: [{
    validator: (rule, value, callback) => {
      if (!supplyForm.value.types && !supplyForm.value.specifications) {
        callback(new Error('型号和规格至少输入一项'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  }],
  specifications: [{
    validator: (rule, value, callback) => {
      if (!supplyForm.value.types && !supplyForm.value.specifications) {
        callback(new Error('型号和规格至少输入一项'));
      } else {
        callback();
      }
    },
    trigger: 'blur'
  }]
});
// 监听dataList变化，筛选出有子节点的父级数据
watch(dataList, (newValue, oldValue) => {
  optionsParents.value = [];
  newValue.forEach(item => {
    if (item.childMaterial && item.childMaterial.length > 0) {
      optionsParents.value.push(item);
    }
  });  
})

const handleBeforeUnload = (event) => {
  if(!isExport.value){
    // 取消默认行为
    event.preventDefault();
      // 现代浏览器需要将 returnValue 属性设置为非空字符串
      event.returnValue = '';
      return '';
    }
};

onBeforeUnmount(() => {
    window.removeEventListener('beforeunload', handleBeforeUnload);
});

onMounted(() => {
  window.addEventListener('beforeunload', handleBeforeUnload);
   // 从 history state 中获取数据
  if (history?.state?.queryCode) {
    // 处理数据
    dataInfo.value.id = history.state.id;
    dataInfo.value.title1 = history.state.cumtomName;
    dataInfo.value.title2 = history.state.queryContent;
    dataInfo.value.title3 = history.state.queryCode;
    dataInfo.value.items = JSON.parse(history.state.lists);
    options.value = [{ value:dataInfo.value.title1, label: dataInfo.value.title}];
    value.value = dataInfo.value.title1;
    dataList.value = JSON.parse(history.state.lists);//询价数据
    // console.log("🚀 ~ onMounted ~ dataList.value:", dataList.value)
    
  }else{
      getList();
  }
});

// 添加获取颜色类名的方法
function getColorClass(row) {
  if (row.materialID >= 1) {
    return 'green';
  } else if (row.materialID === -1) {
    return 'yellow';
  } else if (row.materialID === 0) {
    return 'red';
  }
  return 'black';
}

/** 新增物料 */
function addWl(row) {
  rowForm.value = { ...row }; // 使用对象的副本避免引用问题
  proxy.$modal.loading("正在加载数据，请稍候...");
  // 重置表单为初始状态  等待所有数据加载完成后再打开弹窗
  resetSupplyForm();
  getAlldata().then(() => {
    proxy.$modal.closeLoading();
    supplyDialogTitle.value = "新增物料";
    // 根据row设置一些初始值
    if (row) {
      supplyForm.value.name = row.billName || null; // 名称
      supplyForm.value.specifications = row.billSpecifications || null; // 规格
      supplyForm.value.types = row.billTypes || null; // 型号
      supplyForm.value.remaining = row.billRemaining || null; // 数量
      supplyForm.value.unit_V = row.billUnit || null; // 单位
      if(row.billUnit){
        const defaultLabel = row.billUnit;
        const selectedOption = Propsoptions5.value.find(item => item.name === defaultLabel);
        if (selectedOption) {
          supplyForm.value.unit = selectedOption.id;
        }
      }
       // 打开弹窗
      showSupplyDialog.value = false;
      showSupplyDialog.value = true;

    }
  }).catch(error => {
    proxy.$modal.closeLoading();
    proxy.$modal.msgError("加载数据失败，请稍后重试");
    console.error("加载数据失败:", error);
  });
}

/** 重置物料表单 */
function resetSupplyForm() {
  supplyForm.value = {
    id: null,
    classCode: null,
    classNum: null,
    name: null,
    reName: null,
    resource: null,
    specifications: null,
    types: null,
    styles: null,
    colors: null,
    level: null,
    remaining: 0,
    unit: null,
    unit_V: '单位',
    manufacturer: null,
    barcode: null,
    warmLevel: 0,
    takeTime: 0,
    price: {
      cost: 0,
      profitRate: 1,
      taxRate: 1,
      discount: 1,
      preferential: 0,
      price1Show: 0
    },
    repository: null
  };
}


// 根据选择的单位ID查找对应的单位名称
function handleSupplyChangeOpt5(value) {
  const selectedUnit = Propsoptions5.value.find(item => item.id === value);
  if (selectedUnit) {
    supplyForm.value.unit_V = selectedUnit.name;
  }
}
// 新增计算属性
const displayCost = computed({
  get() {
    if (costUnit_.value === '元') {
      // 为了避免浮点数精度问题，将分转换为元时先除以 100 再取整
      return Math.round(rowForm.value.unitCost) / 100;
    }
    return rowForm.value.unitCost;
  },
  set(newValue) {
    if (costUnit_.value === '元') {
      // 为了避免浮点数精度问题，将元转换为分时先乘以 100 再取整
      rowForm.value.unitCost = Math.round(newValue * 100);
    } else {
      rowForm.value.unitCost = newValue;
    }
    UpdateSellingPrice2();
  }
});

// 修改 handleCommand 函数
function handleCommand(e) {
  costUnit_.value = e;
  // 不需要再修改 form 的原始值 触发售价更新
  UpdateSellingPrice2();
}

// 新增成本监听逻辑
function handleSupplyUpdateSellingPrice() {
   // 成本监听逻辑 （当成本大于5000时，利润率为1.33，否则为1.35）
  //  if(supplyForm.value.price.cost >= 5000){
  //     supplyForm.value.price.profitRate = 1.33;
  //   }else{
  //     supplyForm.value.price.profitRate = 1.35;
  //   }

    const { cost, taxRate, profitRate, discount, preferential } = supplyForm.value.price;
    const price1Show = (cost * taxRate * profitRate * discount - preferential)/100;
    // 修改此处，保留三位小数，最后一位四舍五入
    supplyForm.value.price.price1Show = parseFloat(price1Show.toFixed(3));
}

function UpdateSellingPrice2() {
  // 成本监听逻辑
  // if (rowForm.value.unitCost >= 5000) {
  //   rowForm.value.profitRate = 1.33;
  // } else {
  //   rowForm.value.profitRate = 1.35;
  // }
  const { unitCost, taxRate, profitRate, discount, preferential } = rowForm.value;
  let price1Show = (unitCost * taxRate * profitRate * discount - preferential) / 100;
  // 保留三位小数，最后一位四舍五入
  rowForm.value.unitPrice = parseFloat(price1Show.toFixed(3));
}
// 筛选组件模板
const dialogVisible = ref(false);
const materialTableRef = ref(null);
//选中物料
function selWl(index,row) { 
  isZ.value = row?.parentsID>0?true:false; //是否是子节点
  selIndex.value = dataList.value.findIndex(item => item.autoBillID === row.autoBillID);
  selId.value = row.materialID;
  if(isZ.value){ //如果是子
    // 查询父节点 index索引
    selId.value = 1;
    selItem.value = row;
    // 子row匹配上层 父修改
    selIndex.value = dataList.value.findIndex(item => item.autoBillID === row.parentsID);
  }
  // row.path ==3 ==4 只筛选规格/型号  名称去除
  queryParams2.value.name = row.path==3 || row.path==4? null : row.billName; 
  queryParams2.value.specifications = row.billSpecifications || null; 
  dialogVisible.value = true;
  handleTableQuery(queryParams2.value);
}
//模糊搜索
function onInput() {
  handleTableQuery(queryParams2.value);
}

//选后重新赋值
function handleMaterialSelect(row) {
  const index = selIndex.value;
   
  if(!isZ.value){ //父节点
    nextTick(() => {
      dataList.value[index].materialID = row.id; //
      dataList.value[index].unitCost = row.price.cost ?? 0; // 成本(分)
      dataList.value[index].unitCost1 = Number((row.price.cost / 100).toFixed(2)) ?? 0; // 成本(元)
      dataList.value[index].unitPrice = Number(row.price.price1Show) ?? 0; // 单价(元)
      dataList.value[index].totalCost = Number(dataList.value[index].unitCost1 * dataList.value[index].billRemaining).toFixed(2) ?? 0; //总成本
      dataList.value[index].totalPrice = Number(dataList.value[index].unitPrice * dataList.value[index].billRemaining).toFixed(2) ?? 0; //总单价
    });
  }else{
     // index选中父索引  // selItem.value 父索引下的数据
    console.log( dataList.value[index])
    let list =  dataList.value[index].childMaterial;
    const index2 = list.findIndex(item => item.autoBillID === selItem.value.autoBillID);
      nextTick(() => {
        dataList.value[index].childMaterial[index2].materialID = row.id; //
        dataList.value[index].childMaterial[index2].unitCost = row.price.cost ?? 0; // 成本(分)
        dataList.value[index].childMaterial[index2].unitCost1 = Number((row.price.cost / 100).toFixed(2)) ?? 0; // 成本(元)
        dataList.value[index].childMaterial[index2].unitPrice = Number(row.price.price1Show) ?? 0; // 单价(元)
        dataList.value[index].childMaterial[index2].totalCost = Number(dataList.value[index].childMaterial[index2].unitCost1 * dataList.value[index].childMaterial[index2].billRemaining).toFixed(2) ?? 0; //总成本
        dataList.value[index].childMaterial[index2].totalPrice = Number(dataList.value[index].childMaterial[index2].unitPrice * dataList.value[index].childMaterial[index2].billRemaining).toFixed(2) ?? 0; //总单价
    });
  }
  
}
// 处理表格查询
function handleTableQuery(params) {
  materialTableRef.value.setLoading(true);
  proxy.quote_API.GetMaterialPriceList(params).then(response => {
    materialTableRef.value.setDataList(response.data);
    if(response.data?.length<1){
      proxy.$modal.msgError("没有找到匹配条件的物料~");
    }
  }).finally(() => {
    materialTableRef.value.setLoading(false);
  })
}
/** 多选框选中数据 */
function handleSelectionChange2(selection) {
  ids.value = selection.map(item => item.roleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 	根据Excel文件明获取列表 */
function getList() {
  if(!reName.value) return;
  loading.value = true;
  proxy.quote_API.GetPomlistByFileNameEX({reName:reName.value}).then(response => {
      dataInfo.value = response.data || {};
      options.value = [{ value:response.data.title1, label: response.data.title}];
      value.value = response.data.title1;
      dataList.value = response.data.items || [];
      loading.value = false;
  }).finally(() => {
    loading.value = false;
  })

}
// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
  clearTimeout(timer);
  timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
  // getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除名称"' + row.billName + '"的数据项?').then(function () {
    // dataList.value = dataList.value.filter(item => item.autoBillID!== row.autoBillID);
    deleteChildNodes(row.autoBillID);
  }).finally(() => {
    proxy.$modal.msgSuccess("删除成功");
  })
}

// 需要递归dataList，找到autoBillID对应的项，并删除其子项
function deleteChildNodes(nodeId) {
  const recursiveDelete = (arr) => {
    for (let i = arr.length - 1; i >= 0; i--) {
      if (arr[i].autoBillID === nodeId) {
        arr.splice(i, 1);
        return true; // 这里会立即终止当前递归层级的循环
      }
      if (arr[i].childMaterial?.length) {
        // 仅执行删除操作，不再处理空数组
        recursiveDelete(arr[i].childMaterial);
      }
    }
    return false;
  };
  recursiveDelete(dataList.value);
}
/** 临时保存操作 */
function handleSave() {
  loading.value = true;
  proxy.quote_API.PostToServerForSave({
    title1: dataInfo.value.title1,
    title2: dataInfo.value.title2,
    title3: dataInfo.value.title3,
    items: dataList.value
  }).then(response => {
    proxy.$modal.msgSuccess("已保存成功,可在保存记录中查看");
  }).finally(() => {
    loading.value = false;
  });
  
}
/** 匹配按钮操作 */
function handleMatching() {
  proxy.$modal.loading("正在精准匹配报价，请稍候...");
  proxy.quote_API.PostPomlistToMatchPrice({
    title1: dataInfo.value.title1,
    title2: dataInfo.value.title2,
    title3: dataInfo.value.title3,
    items: dataList.value
  }).then(response => {
      dataInfo.value = response.data || {};
      options.value = [{ value:response.data.title1, label: response.data.title}];
      value.value = response.data.title1;
      dataList.value = response.data.items || [];
  }).finally(() => {
    proxy.$modal.closeLoading();
  });
};


/** 导出按钮操作 */
function handleExport() {
  isExport.value = true;
  proxy.$modal.loading("正在导出报价，请稍候...");
  proxy.quote_API.XunJiaServerForSave({
    title1: dataInfo.value.title1,
    title2: dataInfo.value.title2,
    title3: dataInfo.value.title3,
    items: dataList.value
  }).then(response => {
    // 返回的是url
    if (response.code === 1 && response.data) {
      // 创建一个隐藏的a标签用于下载
      const link = document.createElement('a');
      link.href = response.data;
      link.setAttribute('download', `报价单_${dataInfo.value.title1}_${new Date().getTime()}.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }).finally(() => {
    setTimeout(() => {
      isExport.value = false;
      proxy.$modal.closeLoading();
    }, 500);
  });
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "选择文件";
  upload.open = true;
};

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  if (response.code == 1) {
     reName.value = response.data.reName;
     getList();
  }
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

// 添加计算属性 canExport 来判断是否可以导出报价
const canExport = ref(false);
/**
 * 递归检查子节点的状态
 * @param {Array} children - 子节点数组
 * @returns {boolean} - 如果所有子节点的状态都满足条件，则返回 true，否则返回 false
 */
 const checkChildNodes = (children) => {
  // 使用 every 方法遍历子节点数组
  return children.every(child => {
    // 检查当前子节点的状态是否为 1 且 materialID 不为 0  && child.materialID !== 0
    if (child.status === 1) {
      // 检查当前子节点是否有子节点
      if (child.childMaterial && child.childMaterial.length > 0) {
        // 如果有子节点，递归调用 checkChildNodes 函数检查子节点的子节点
        return checkChildNodes(child.childMaterial);
      }
      // 如果没有子节点，当前子节点满足条件
      return true;
    }
    // 当前子节点不满足条件
    return false;
  });
};
watchEffect(() => {
  // 检查 dataList 是否有数据
  if (dataList.value?.length > 0) {
    // 使用 every 方法遍历 dataList 数组
    canExport.value = dataList.value.every(item => {
      // 检查当前项的状态是否为 1 且 materialID 不为 0 && item.materialID !== 0
      if (item.status === 1 ) {
        // 检查当前项是否有子节点
        if (item.childMaterial && item.childMaterial.length > 0) {
          // 如果有子节点，调用 checkChildNodes 函数检查子节点的状态
          return checkChildNodes(item.childMaterial);
        }
        // 如果没有子节点，当前项满足条件
        return true;
      }
      // 当前项不满足条件
      return false;
    });
  } else {
    // 如果 dataList 没有数据，设置 canExport 为 false
    canExport.value = false;
  }
});

/** 重置新增的表单以及其他数据  */
function reset() {
  rowForm.value = {
    autoBillID: null,
    billID:null,
    billName: null,
    billMaterialNO: null,
    billSpecifications:null,
    billTypes: null,
    billRemaining: 1,
    billUnit:null,
    billManufacturer: null,
    status: 0,
    materialID: 0, //默认添加 0 未匹配  -1为匹配到多个，其余为一对一匹配成功
    unitCost: 0,
    profitRate: 0,
    taxRate: 0,
    discount: 0,
    preferential: 0,
    unitPrice: 0,
    priceShow: 0,
    totalPrice: 0
  };
  costUnit_.value = '元';
  proxy.resetForm("roleRef");
}

// 计算成本总和并保留两位小数的方法，解决浮点数精度问题
const getTotalCost = (row, type) => {
  // 只有当 row.childMaterial 存在且长度大于 0 时才进行总和计算
  if (row.childMaterial && row.childMaterial.length > 0) {
    if(type === 'totalCost' || type === 'totalPrice') {
      let maxDecimals = row.childMaterial.reduce((max, child) => {
        let decimalLength = String(Number(child[type]) || 0).split('.')[1]?.length || 0;
        return Math.max(max, decimalLength);
      }, 0);
      let multiplier = Math.pow(10, maxDecimals);
      let total = row.childMaterial.reduce((sum, child) => {
        return sum + Math.round((Number(child[type]) || 0) * multiplier);
      }, 0);
      if(type == 'totalPrice'){
        total = total*Number(row.billRemaining);
      }
      
      return (total / multiplier).toFixed(2);
    }else{
      return '-'
    }
  }
  // 其他情况直接返回接口返回的数据
  return row[type];
};

/** 新增 */
function handleAdd() {
  reset();
  rowDisabled.value = false;//禁用权限关闭
  open.value = true;
  title.value = "添加报价数据";
}

/** 修改 */
function handleUpdate(row) {
  // reset();
  rowDisabled.value = true; // 禁用权限打开
  rowForm.value = { ...row }; // 使用对象的副本避免引用问题
  open.value = true;
  title.value = "修改报价数据";
}

// 获取表格组件的引用
const tableRef = ref(null);

// 新增物料--且更新报价
function handleSupplySubmit() {
  proxy.quote_API.AddMaterials({
    ...supplyForm.value,
  }).then(response => {
    proxy.$modal.msgSuccess("物料新增成功");
    showSupplyDialog.value = false;
    getOneUpdate();
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      // 新增报价
      if (!rowDisabled.value) {
        // 创建 rowForm 的副本
        let lastId = null;
        if(dataList.value[dataList.value.length - 1]?.childMaterial?.length>0){
          // 如果最后父节点有子节点 找到最后一个子元素的 autoBillID
          lastId = (dataList.value[dataList.value.length - 1].childMaterial[dataList.value[dataList.value.length - 1].childMaterial.length - 1].autoBillID)+1;
        }else{
          // 如果最后父节点没有子节点 就是最后一个autoBillID
          lastId = (dataList.value[dataList.value.length - 1].autoBillID)+1;
        }
        const newRow = { ...rowForm.value,autoBillID:lastId };
        // dataList.value.push(newRow);
        open.value = false;
        getOneUpdate2(newRow); //跟换单独最新的报价
        proxy.$modal.msgSuccess('新增成功');
        // 滚动到最后一行
        scrollToLastRow();
      } else {
        // 修改物料--且更新报价
        proxy.quote_API.EditMaterialPrice({
          cost: rowForm.value.unitCost,
          profitRate: rowForm.value.profitRate,
          taxRate: rowForm.value.taxRate,
          discount: rowForm.value.discount,
          preferential: rowForm.value.preferential,
          materialID: rowForm.value.materialID
        }).then(response => {
          getOneUpdate();
          open.value = false;
          proxy.$modal.msgSuccess('编辑成功');
        });
      }
    }
  });
}
// 覆盖最新单条数据
function getOneUpdate(){
  proxy.quote_API.PostPomlistToMatchPrice(  {
    title1: dataInfo.value.title1,
    title2: dataInfo.value.title2,
    title3: dataInfo.value.title3,
    items: [rowForm.value]
  }).then(response => {
      const oneItem = response.data.items[0];
       // 判断是否是父节点 还是子节点 oneItem.parentsID有值就是子节点
       if (oneItem.parentsID) {
        // 找到父节点的索引
        const parentIndex = dataList.value.findIndex(item => item.autoBillID === oneItem.parentsID);  
        // 找到父节点的子节点数组
        const childMaterial = dataList.value[parentIndex].childMaterial || [];
        // 找到子节点的索引
        const childIndex = childMaterial.findIndex(item => item.autoBillID === oneItem.autoBillID);
        // 更新子节点
        childMaterial[childIndex] = oneItem;
      } else {
        // 找到父节点的索引
        const parentIndex = dataList.value.findIndex(item => item.autoBillID === oneItem.autoBillID); 
        // 更新父节点
        dataList.value[parentIndex] = oneItem;
      }
  })
}
// 新增最新单条数据
function getOneUpdate2(newRow){
  proxy.quote_API.PostPomlistToMatchPrice(  {
    title1: dataInfo.value.title1,
    title2: dataInfo.value.title2,
    title3: dataInfo.value.title3,
    items: [newRow]
  }).then(response => {
      const oneItem = response.data.items[0];
      // 判断是否是父节点 还是子节点 oneItem.parentsID有值就是子节点
      if (oneItem.parentsID) {
        // 找到父节点的索引
        const parentIndex = dataList.value.findIndex(item => item.autoBillID === oneItem.parentsID);  
        // 找到父节点的子节点数组
        const childMaterial = dataList.value[parentIndex].childMaterial || [];
        // 新增到子节点数组
        childMaterial.push(oneItem);
      } else {
        // 新增到父节点数组
        dataList.value.push(oneItem);
      }
  })
}

// 滚动到最后一行的方法
function scrollToLastRow() {
  if (tableRef.value) {
    // 等待DOM更新
    nextTick(() => {
      const tableBody = tableRef.value.$el.querySelector('.el-table__body-wrapper');
      if (tableBody) {
         const rows = tableBody.querySelectorAll('.el-table__row');
          let totalHeight = 0;
          rows.forEach(row => {
            totalHeight += row.offsetHeight;
          });
        tableRef.value.setScrollTop(totalHeight)
      }
    });
  }
}
/** 手动关闭 */
function handleCascaderChange(e) {
  // 主动关闭弹层
  cascaderRef.value.togglePopperVisible(false)
}
// 复制
async function copy(text) {
  try {
    await navigator.clipboard.writeText(text);
    proxy.$modal.msgSuccess('复制成功');
  } catch (err) {
    console.log(err);
  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 分类字典数据 */
function getAlldata() {
  // 创建一个Promise数组来存储所有API请求
  const promises = [];
  // 分类--树数据
  const promise1 = proxy.quote_API.GetClassCodeByGroup({}).then(response => {
    response.data.forEach(element => {
      element.children = []
    })
    const data = proxy.handleTree(response.data, 'classCode', 'groupCode');
    Propsoptions.value = data[0].children || [];
    supplyForm.value.classCode = supplyForm.value.classCode ? supplyForm.value.classCode : Propsoptions.value[0].classCode;
  });
  promises.push(promise1);

  // 字典数据--物料来源
  const promise2 = proxy.quote_API.GetCodeForDPL({
    code_Group: 1
  }).then(response => {
    Propsoptions2.value = response.data || [];
    supplyForm.value.resource = supplyForm.value.resource ? supplyForm.value.resource : Propsoptions2.value[0].id;
  });
  promises.push(promise2);

  // 字典数据--物料类别
  const promise3 = proxy.quote_API.GetCodeForDPL({
    code_Group: 2
  }).then(response => {
    Propsoptions3.value = response.data || [];
    supplyForm.value.styles = supplyForm.value.styles ? supplyForm.value.styles : Propsoptions3.value[0].id;
  });
  promises.push(promise3);

  // 字典数据--物料等级
  const promise4 = proxy.quote_API.GetCodeForDPL({
    code_Group: 3
  }).then(response => {
    Propsoptions4.value = response.data || [];
    supplyForm.value.level = supplyForm.value.level ? supplyForm.value.level : Propsoptions4.value[0].id;
  });
  promises.push(promise4);
  // 字典数据--物料单位
  const promise5 = proxy.quote_API.GetCodeForDPL({
    code_Group: 4
  }).then(response => {
    Propsoptions5.value = response.data || [];
    supplyForm.value.unit = supplyForm.value.unit ? supplyForm.value.unit : Propsoptions5.value[0].id;
    supplyForm.value.unit_V = supplyForm.value.unit_V ? supplyForm.value.unit_V : Propsoptions5.value[0].name;
  });
  promises.push(promise5);

  // 字典数据--物料仓库
  const promise6 = proxy.quote_API.GetCodeForDPL({
    code_Group: 6
  }).then(response => {
    Propsoptions6.value = response.data || [];
    supplyForm.value.repository = supplyForm.value.repository ? Number(supplyForm.value.repository) : Propsoptions6.value[0].id;
  });
  promises.push(promise6);
  // 返回Promise.all，等待所有请求完成
  return Promise.all(promises);
}
</script>

<style lang="scss" scoped>
.el-input-number {
  width: 190px;
}
.el-table__body-wrapper {
  overflow-y: auto;
}
.expand-placeholder {
  color: #666;
  margin-left: 24px; /* 保持与展开箭头对齐 */
}
.required-star {
  color: #F56C6C;
  margin-right: 4px;
}
.legend-container {
  text-align: right;
  display: flex;
  font-size: 14px;
  justify-content: flex-end;
  align-items: center;

}

.legend-item {
  display: inline-block;
  margin-left: 16px;
}

.legend-color {
  display: inline-block;
  width: 12px;
  height: 12px;
  margin-right: 5px;
}

.green_bg {
  background-color: #67C23A;
}

.yellow_bg {
  background-color: #E6A23C;

}

.red_bg {
  background-color: #F56C6C;
}
.green {
  color: #67C23A;
  font-weight: bold;
}

.yellow {
  color: #E6A23C;
    font-weight: bold;
}

.red {
  color: #F56C6C;
    font-weight: bold;
}
.black{
  color: #333;
}
</style>
